﻿using Microsoft.Extensions.Options;
using NCD.ORMDbContext.Dapper;
using NCD.ORMDbContext.Entities;
using NCD.ORMDbContext.Enums;
using Newtonsoft.Json;
using SqlSugar;
using System.Data;

namespace NCD.ORMDbContext.SqlSugarOrm
{

    /// <summary>
    /// 数据库上下文
    /// </summary>
    public abstract class SqlSugarDbContext
    {

        /// <summary>
        /// 用来处理事务多表查询和复杂的操作
        /// </summary>
        public SqlSugarClient DbContext;
        /// <summary>
        /// 配置信息
        /// </summary>
        private readonly SqlSugarDbContextOptions _options;

        protected abstract IDbConnection CreateConnection(string connectionString, DbTypeNameEnum dbType);

        public SqlSugarDbContext(IOptions<SqlSugarDbContextOptions> optionsAccessor) 
        {

            _options = optionsAccessor.Value;

            var _connection = CreateConnection(_options.Connection, _options.DbType);


            //HitRate 数据库命中率 http://www.donet5.com/home/doc?masterId=1&typeId=1209
            //1.如果存在事务所有操作都走主库，不存在事务 修改、写入、删除走主库，查询操作走从库
            DbContext = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = GetDbType(_options.DbType),
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,
                ConnectionString = _connection.ConnectionString
            });

            //每次Sql执行前事件
            DbContext.Aop.OnLogExecuting = (s, p) =>
            {
                //监控执行超时的方法
                if (DbContext.Ado.SqlExecutionTime.TotalSeconds > 5)
                {
                    //代码CS文件名
                    var fileName = DbContext.Ado.SqlStackTrace.FirstFileName;
                    //代码行数
                    var fileLine = DbContext.Ado.SqlStackTrace.FirstLine;
                    //方法名
                    var methodName = DbContext.Ado.SqlStackTrace.FirstMethodName;
                }

            };
        }

        #region 数据表1

        public SimpleClient<UserInfo> UserInfoDb => new SimpleClient<UserInfo>(DbContext);//测试表

        #endregion


        private SqlSugar.DbType GetDbType(DbTypeNameEnum typeName)
        {

            SqlSugar.DbType dbType = SqlSugar.DbType.MySql;
            switch (typeName)
            {
                case DbTypeNameEnum.MsSql:
                    dbType = SqlSugar.DbType.SqlServer;
                    break;
                case DbTypeNameEnum.PgSql:
                    dbType = SqlSugar.DbType.PostgreSQL; break;
                case DbTypeNameEnum.Oracle:
                    dbType = SqlSugar.DbType.Oracle; break;

            }
            return dbType;
        }

    }


}
